# __author__ = 'GuanFengyu'


import os
import tkinter.filedialog as fd
import tkinter.messagebox as mb
from tkinter import *

import xlrd
import xlwt

from myXlsStyles import styleCommon


class DecisionTableToCase1:
    def __init__(self):
        self.frame = Frame(width=550, height=350)
        self.text = "判定表生成测试案例"
        self.help = "Dt2xls工具使用说明"
        self.var_xls = StringVar()
        self.set_frame()

        # self.var_xls.set('D:/WorkG/GenerateTestCasePy3/TestData/decision_table1.xls')
        # self.decision_table_to_case()
    
    # 选择xls文件
    def select_xls(self):
        path = fd.askopenfilename(initialdir = os.getcwd(),
                                  filetypes = [('xls files', '*.xls')])
        self.var_xls.set(path)
    
    # 判定表生成测试案例
    def decision_table_to_case(self):
        # 打开xls文件
        xlsFilename = self.var_xls.get()
        
        if xlsFilename == '':
            mb.showerror(title = "提示", message = "%s 文件路径不存在" % xlsFilename)
            return
        if not xlsFilename.endswith('.xls'):
            mb.showerror(title = '提示', message = '选择文件非xls结尾')
            return
        
        workbook = xlrd.open_workbook(xlsFilename,formatting_info=True)
        sheet_names = workbook.sheet_names()

        workbook_write = xlwt.Workbook(encoding='utf-8')

        for sheet_name in sheet_names:
            sheet = workbook.sheet_by_name(sheet_name)
            conditions, results = self.read_sheet(sheet)
            self.write_excel(workbook_write, sheet.name, conditions, results)
        try:
            wb_save_filename = self.var_xls.get()[:-4]+"_Case.xls"
            workbook_write.save(wb_save_filename)
            mb.showinfo(title = '提示',message = wb_save_filename + u'文件已保存到对应目录')
        except Exception:
            mb.showerror(title = '提示', message = u'没有选择保存文件名')

    
    def read_sheet(self, sheet):
        condition_keywords = [u'条件']
        condition_positive = [u'T', u'1', 1]
        condition_negtive  = [u'F', u'0', 0]
        condition_positive_text = u' 满足'
        condition_negtive_text  = u' 不满足'
        step_text = u'步骤'
        result_keywords = [u'结果',u'动作']
        result_positive = [1,u'X']
        
        nrows = sheet.nrows
        ncols = sheet.ncols

        # 验证表格非空
        if nrows == 0 or ncols == 0:
            print('sheet maybe empty')
            return
        print('Sheet name:' + sheet.name)
        
        # 读取合并单元格，查找其中带关键字的
        condition_kw_rs, condition_kw_re, condition_kw_cs, condition_kw_ce = [-1, -1, -1, -1]    # [起始行，结束行，起始列，结束列]
        for crange in sheet.merged_cells:
            cell_value = sheet.cell_value(crange[0],crange[2])
            for keyword in condition_keywords:
                if cell_value.find(keyword) >= 0:               
                    condition_kw_rs, condition_kw_re, condition_kw_cs, condition_kw_ce = crange 
                    break
        if condition_kw_rs == -1:
            print('sheet format error')
            return
        
        # 获得条件名称
        condition_cnt = condition_kw_re - condition_kw_rs  # 条件个数
        condition_cols = condition_kw_ce   # 条件列
        print('Condition number:' + str(condition_cnt))
        
        conditions = []
        for condition_index in range(condition_kw_rs, condition_kw_re):
            conditions.append(sheet.cell_value(condition_index, condition_cols))
        
        # 获得结果
        results = []
        result_kw_rs, result_kw_re, result_kw_cs, result_kw_ce = [-1, -1, -1, -1]    # [起始行，结束行，起始列，结束列]
        for crange in sheet.merged_cells:
            cell_value = sheet.cell_value(crange[0], crange[2])
            for keyword in result_keywords:
                if cell_value.find(keyword) >= 0:
                    result_kw_rs, result_kw_re, result_kw_cs, result_kw_ce = crange
                    break
        if result_kw_rs == -1:
            for result_index in range(condition_kw_re + 1, nrows):
                res_str = sheet.cell_value(result_index, 0)
                if res_str:
                    results.append(res_str)
        else:
            # 获得结果名称
            for result_index in range(result_kw_rs,result_kw_re):
                results.append(sheet.cell_value(result_index, result_kw_ce))
        print(results)
        

        # 获得Case个数
        case_cols = condition_cols + 1
        case_cnt = ncols - case_cols
        print('Case number:' + str(case_cnt))
        # 按每个Case处理
        cases = []
        cases_result = []
        for case_index in range(case_cols, ncols):
            # 读取每个Case
            case = []
            step_index = 1
            for condition_index in range(condition_kw_rs, condition_kw_re):
                case_condition = step_text + str(step_index) + ': ' + conditions[condition_index - condition_kw_rs]
                case_value = sheet.cell_value(condition_index, case_index)
                if case_value in condition_positive:
                    case_condition += condition_positive_text
                elif case_value in condition_negtive:
                    case_condition += condition_negtive_text
                else:
                    continue
                step_index += 1
                case.append(case_condition)
            # 拼接
            case_str = u';\n'.join(case) + '.'
            
            cases.append(case_str)
            # case restult
            if result_kw_rs == -1:
                case_result_value = sheet.cell_value(condition_kw_re, case_index)
                cases_result.append(results[int(case_result_value)-1])
            else:
                for result_index in range(result_kw_rs,result_kw_re):
                    if sheet.cell_value(result_index, case_index) in result_positive:
                        cases_result.append(results[result_index - result_kw_rs])
                        break
      
        return cases, cases_result

    def write_excel(self, wb, sheetname, conditions, results):
        if wb is None:
            return
        nrows = len(conditions)
        if len(results) != nrows:
            return

        booksheet = wb.add_sheet(sheetname, cell_overwrite_ok=True)
        
        booksheet.write(0, 0, '步骤描述', styleCommon)
        booksheet.write(0, 1, '预期结果', styleCommon)
        booksheet.col(0).width = 256 * 40
        booksheet.col(1).width = 256 * 40
        for i in range(0, nrows):
            booksheet.write(i + 1, 0, conditions[i], styleCommon)
            booksheet.write(i + 1, 1, results[i], styleCommon)

    def set_frame(self):
        # 标签
        Label(self.frame,text = 'excel文件:').place(x=30, y=90)
        # 输入框entry_txt
        entry_xls = Entry(self.frame,textvariable=self.var_xls,width=43)
        entry_xls.place(x=120, y=90)
        # 按钮
        Button(self.frame,text = '浏览',command = self.select_xls,height = 1).place(x=490, y=85)
        Button(self.frame, text='生成excel案例', command=self.decision_table_to_case).place(x=230, y=200)
